package com.zyx.nettypro.netty.sticky.problem;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Yaxi.Zhang
 * @since 2021/9/24 10:03
 */
public class MyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private final AtomicInteger count = new AtomicInteger();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        byte[] buffer = new byte[msg.readableBytes()];
        // 字节码转为字符串
        msg.readBytes(buffer);

        String message = new String(buffer, CharsetUtil.UTF_8);

        System.out.println("服务器接收到数据: " + message);
        System.out.println("客户端发送数据的数量: " + count.incrementAndGet());

        // 服务器给客户端回送一个信息
        ByteBuf info = Unpooled.copiedBuffer(UUID.randomUUID().toString() + " ", CharsetUtil.UTF_8);
        ctx.writeAndFlush(info);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("exception =====>>>>> " + cause.getMessage());
        ctx.close();
    }
}
